package mao.leetcode.offer;

/**
 * @author Totoro
 * @date 2020/6/28
 * @explain:
 */
public class Interview35 {


// Definition for a Node.
    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    static class Solution {
        public Node copyRandomList(Node head) {
            if (null == head) return null;
            Node node = head;
            while (node != null) {
                Node copyed = new Node(node.val);
                copyed.next = node.next;
                node.next = copyed;
                node = node.next.next;
            }

            node = head;
            while (null != node) {
                if (node.random != null) {
                    node.next.random = node.random.next;
                } else {
                    node.next.random = null;
                }
                node = node.next.next;
            }

            node = head;
            Node newHead = head.next;
            Node newNode = newHead;
            while (null != node) {
                node.next = node.next.next;
                newNode.next = newNode.next.next;
                node = node.next;
                newHead = newNode.next;
            }
            return newHead;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Node node_1 = new Node(1);
        Node node_2 = new Node(2);
        Node node_3 = new Node(3);

        node_1.next = node_2;
        node_2.next = node_3;
        node_3.random = node_1;

        solution.copyRandomList(node_1);
    }
}
